package com.yinwq.shorturl.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Pattern;

/**
 * @author xiechengyao
 * @version $Id: DateUtil, v 0.1 2018- 06- 05 11: 08 xiechengyao Exp $$
 * @description: 时间转化工具类
 * @name 时间转化工具类
 */
public class DateUtil {

    private static Logger logger = LoggerFactory.getLogger(DateUtil.class);

    public static final String DEFUALT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String LONG_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
    public static final String DEFAULT_TIME_PATTERN = "HH:mm:ss";
    public static final String TIME_END = "23:59:59";

    public static Date parseByYMD(String str) throws Exception {
        if(StringUtils.isEmpty(str)){
            return null;
        }
        return new SimpleDateFormat(DEFAULT_DATE_PATTERN).parse(str);
    }

    public static Date parseByPattern(String str, String pattern) throws Exception {
        if(StringUtils.isEmpty(str)){
            return null;
        }
        return new SimpleDateFormat(pattern).parse(str);
    }

    public static String formateDate(Date date, String dateTimePattern) throws Exception {
        if(date == null){
            return null;
        }
        return new SimpleDateFormat(dateTimePattern).format(date);
    }

    /**
     * @author chenjiebin
     * @date  2018/8/24 14:02
     * @param date  当前时间
     * @param time  加的时间
     * @return {@link Date}
     */
    public static Date addAndReduceTime(Date date,Integer time) throws Exception {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.MINUTE, time);
        Date tomorrow = c.getTime();
        return tomorrow;
    }


    /**
     * @author chenjiebin
     * @date  2018/8/24 14:02
     * @param date  当前时间
     * @param hour  加的时间(小时)
     * @return {@link Date}
     */
    public static Date addHour(Date date,Integer hour) throws Exception {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.HOUR, hour);// 今天加几分钟
        Date tomorrow = c.getTime();
        return tomorrow;
    }


    public static Date getYearFirst(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        return calendar.getTime();
    }

    public static Date dateAddOneDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +1);//+1今天的时间加一天
        return calendar.getTime();
    }

    public static Date dateAddDay(Date date, int addDay){
        if(date == null){
            return date;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +addDay);//今天的时间加 addDay 天
        return calendar.getTime();
    }

    /**
     * 传入日期增加 year年
     * @param date 传入日期
     * @param year 增加年数
     * @return
     */
    public static Date dateAddYear(Date date, int year){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, +year);//
        return calendar.getTime();
    }

    /**
     * 传入日期增加 year年 and 减一天
     * @param date 传入日期
     * @param year 增加年数
     * @return
     */
    public static Date dateAddYearAndReduceOneDay(Date date, int year, int day){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, +year);//加year年
        calendar.add(Calendar.DAY_OF_MONTH, -day);//减day天
        return calendar.getTime();
    }

    /**
     * 传入日期增加 year年 and 减一天
     * @param date 传入日期
     * @param year 增加年数
     * @param second 增加秒数
     * @return
     */
    public static Date dateAddYearAndReduceOneSecond(Date date, int year, int second){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, +year);//加year年
        calendar.add(Calendar.SECOND, -second);//减day天
        return calendar.getTime();
    }

    /**
     * 传入日期修改年，天，秒
     * @param date 传入日期
     * @param year 增加年数
     * @param day 增加天数
     * @param second 增加秒数
     * @return
     */
    public static Date dateAddYearAndAddSecond(Date date, int year, int day, int second){
        if(date == null){
            return date;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, +year);//加year年
        calendar.add(Calendar.DAY_OF_MONTH, +day);//加year年
        calendar.add(Calendar.SECOND, +second);//加second秒
        return calendar.getTime();
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(Date date1,Date date2)
    {
        if(date1 == null || date2 == null){
            return 0;
        }
        int days = (int) Math.ceil( (float)(date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }

    /**
     * 按传入时间基础上减 nowDay天
     * @param date 传入时间
     * @param reduceDay 减天数
     * @return
     */
    public static Date dateReduceDay(Date date, int reduceDay){
        if(date == null){
            return date;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -reduceDay);
        return calendar.getTime();
    }

    /**
     * 按传入时间基础上减 nowDay天
     * @param date 传入时间
     * @param second 修改秒数
     * @return
     */
    public static Date dateModifySecond(Date date, int second){
        if(date == null){
            return date;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, second);
        return calendar.getTime();
    }

    /**
     * 传入日期，判断日期年月是否大于当前日期，大于则返回传入时期的年月+当前年 且加一天，否则返回当前时间
     * @param date
     * @return
     */
    public static Date buildNewestTime(Date date){
        if(date == null){
            return appendDayToZero(date);
        }
        Date timeStart = null;
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int year = calendar.get(Calendar.YEAR) ;
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DATE);
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);

            calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int nowMonth = calendar.get(Calendar.MONTH) + 1;
            int nowDay = calendar.get(Calendar.DATE);
            int nowYear = calendar.get(Calendar.YEAR) ;
            if(year > nowYear){
                /**
                 * 1.分秒为59:59则加一秒
                 * 2.时分秒都为0的都加1天
                 */
                if(minute == 59 && second == 59){
                    timeStart = dateAddYearAndAddSecond(date, 0, 0, 1);
                }else if(hour == 0 && minute == 0 && second == 0){
                    timeStart = dateAddYearAndAddSecond(date, 0, 1, 0);
                }else{
                    timeStart = date;
                }
            }else if(month > nowMonth || (month == nowMonth && day >= nowDay)){
                    calendar = Calendar.getInstance();
                calendar.set(nowYear, month -1, day, hour, minute, second);
                Date time = calendar.getTime();
                /**
                 * 1.分秒为59:59则加一秒
                 * 2.时分秒都为0的都加1天
                 */
                if(minute == 59 && second == 59){
                    timeStart = dateAddYearAndAddSecond(time, 0, 0, 1);
                }else if(hour == 0 && minute == 0 && second == 0){
                    timeStart = dateAddYearAndAddSecond(time, 0, 1, 0);
                }else{
                    timeStart = time;
                }
            }else{
                calendar = Calendar.getInstance();
                calendar.set(nowYear, nowMonth -1, nowDay, 0, 0, 0);
                timeStart = dateAddYearAndAddSecond(calendar.getTime(), 0, 1, 0);;
            }
        } catch (Exception e) {
            logger.error("构造起保时间异常{}", date, e);
        }
        return timeStart;
    }

    /**
     * 传入日期返回第二天00:00:00
     * @param date
     * @return
     */
    public static Date appendDayToZero(Date date){
        if(date == null){
            date = new Date();
        }
        Date timeStart = null;
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int nowMonth = calendar.get(Calendar.MONTH) + 1;
            int nowDay = calendar.get(Calendar.DATE);
            int nowYear = calendar.get(Calendar.YEAR) ;
            calendar = Calendar.getInstance();
            calendar.set(nowYear, nowMonth -1, nowDay, 0, 0, 0);
            timeStart = dateAddYearAndAddSecond(calendar.getTime(), 0, 1, 0);;
        } catch (Exception e) {
            logger.error("appendDayToZore异常{}", date, e);
        }
        return timeStart;
    }


    public static String regFormatDate(String dateStr, String formatStr) throws Exception {
        HashMap<String, String> dateRegFormat = new HashMap<String, String>();
        dateRegFormat.put(
                "^\\d{4}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D+\\d{1,2}\\D*$",
                "yyyy-MM-dd-HH-mm-ss");//2014年3月12日 13时5分34秒，2014-03-12 12:05:34，2014/3/12 12:5:34
        dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}$",
                "yyyy-MM-dd-HH-mm");//2014-03-12 12:05
        dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}\\D+\\d{2}$",
                "yyyy-MM-dd-HH");//2014-03-12 12
        dateRegFormat.put("^\\d{4}\\D+\\d{2}\\D+\\d{2}$", "yyyy-MM-dd");//2014-03-12
        dateRegFormat.put("^\\d{4}\\D+\\d{1,2}\\D+\\d{1,2}$", "yyyy-MM-dd");//2014-03-12
        dateRegFormat.put("^\\d{4}\\D+\\d{2}$", "yyyy-MM");//2014-03
        dateRegFormat.put("^\\d{4}$", "yyyy");//2014
        dateRegFormat.put("^\\d{14}$", "yyyyMMddHHmmss");//20140312120534
        dateRegFormat.put("^\\d{12}$", "yyyyMMddHHmm");//201403121205
        dateRegFormat.put("^\\d{10}$", "yyyyMMddHH");//2014031212
        dateRegFormat.put("^\\d{8}$", "yyyyMMdd");//20140312
        dateRegFormat.put("^\\d{6}$", "yyyyMM");//201403
        dateRegFormat.put("^\\d{2}\\s*:\\s*\\d{2}\\s*:\\s*\\d{2}$",
                "yyyy-MM-dd-HH-mm-ss");//13:05:34 拼接当前日期
        dateRegFormat.put("^\\d{2}\\s*:\\s*\\d{2}$", "yyyy-MM-dd-HH-mm");//13:05 拼接当前日期
        dateRegFormat.put("^\\d{2}\\D+\\d{1,2}\\D+\\d{1,2}$", "yy-MM-dd");//14.10.18(年.月.日)
        dateRegFormat.put("^\\d{1,2}\\D+\\d{1,2}$", "yyyy-dd-MM");//30.12(日.月) 拼接当前年份
        dateRegFormat.put("^\\d{1,2}\\D+\\d{1,2}\\D+\\d{4}$", "dd-MM-yyyy");//12.21.2013(日.月.年)

        String curDate =new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        DateFormat formatter1 =new SimpleDateFormat(formatStr);
        DateFormat formatter2;
        String dateReplace;
        String strSuccess="";

        for (String key : dateRegFormat.keySet()) {
            if (Pattern.compile(key).matcher(dateStr).matches()) {
                formatter2 = new SimpleDateFormat(dateRegFormat.get(key));
                if (key.equals("^\\d{2}\\s*:\\s*\\d{2}\\s*:\\s*\\d{2}$")
                        || key.equals("^\\d{2}\\s*:\\s*\\d{2}$")) {//13:05:34 或 13:05 拼接当前日期
                    dateStr = curDate + "-" + dateStr;
                } else if (key.equals("^\\d{1,2}\\D+\\d{1,2}$")) {//21.1 (日.月) 拼接当前年份
                    dateStr = curDate.substring(0, 4) + "-" + dateStr;
                }
                dateReplace = dateStr.replaceAll("\\D+", "-");
                strSuccess = formatter1.format(formatter2.parse(dateReplace));
                break;
            }
        }
        if(StringUtils.isEmpty(strSuccess)){
            throw new Exception("日期格式无效");
        }
        return strSuccess;
    }


    /**
     * 获取某年最后一天日期
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year){
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }
    public static Date getStartTime() {
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = todayStart.atZone(zone).toInstant();
        return Date.from(instant);
    }

    public static Date getEndTime() {
        LocalDateTime todayStart = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = todayStart.atZone(zone).toInstant();
        return Date.from(instant);
    }


    public static void main(String[] args) {
        System.out.println(getYearLast(2019));
    }

    public static String splitTime(String updateTimeEnd, String time) {
        return updateTimeEnd + " " + time;
    }
}
